﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class touchscreen_buyTicket : System.Web.UI.Page
{
    //Initialize Managers
    private MovieManager movieManager;
    private ReservationManager reservationManager;
    private TicketManager ticketManager;
    private PlanningManager planningManager;
    private bestelling reservation = null;

    //Initialize Variables
    private int MovieID;
    private film selectedMovie = new film();
    private string myScript = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        ticketManager = new TicketManager((debioscoopEntities)Session["db"]);
        planningManager = new PlanningManager((debioscoopEntities)Session["db"]);
        reservationManager = new ReservationManager((debioscoopEntities)Session["db"]);
        //if (Session["Reservation"] != null)
        //{
        //    //Reservation movie
        //    reservation = (bestelling)Session["Reservation"];
        //    selectedMovie = reservation.film;
        //    stap_1.Enabled = false;
        //    backButtonHyperlink.NavigateUrl = "~/touchscreen/Default.aspx";
        //}

        //Get movie ID
        if (!String.IsNullOrEmpty(Request.QueryString["MovieID"]))
        {
            MovieID = int.Parse(Request.QueryString["MovieID"]);

            //Selected movie
            movieManager = new MovieManager((debioscoopEntities)Session["db"]);
            selectedMovie = movieManager.getMovie(MovieID);
        }

        if (IsPostBack)
        {
            //Collect ticket information
            String errorMsg = "";
            String time = timeList.SelectedValue;
            List<kaartje> tickets = new List<kaartje>();

            bool chosenTicket = false;
            foreach (RepeaterItem repeateritem in availableTickets.Items)
            {
                TextBox tb = (TextBox)repeateritem.FindControl("ticket");
                Label lb = (Label)repeateritem.FindControl("ticketName");
                for (int i = 0; i < int.Parse(tb.Text); i++)
                {
                    kaartje tempKaartje = new kaartje();
                    if (int.Parse(tb.Text) > 0)
                    {
                        tempKaartje.abbonement.abbonementnaam = lb.Text;
                        tickets.Add(tempKaartje);
                        chosenTicket = true;
                    }
                }
            }

            //Error handling
            if (time.Equals(""))
            {
                errorMsg += "- U heeft geen tijd gekozen! <br />";
            }
            if (chosenTicket == false)
            {
                errorMsg += "- U heeft geen kaartje gekozen! <br />";
            }
            if (errorMsg.Equals(""))
            {
                TimeSpan selectedMovieTime = new TimeSpan(int.Parse(time.Substring(0, 2)), int.Parse(time.Substring(3,2)), 00);
                planning selectedPlanning = planningManager.getPlanningMovie(selectedMovie.film_id, DateTime.Today, selectedMovieTime);
                int availableSeats = planningManager.getAvailableSeats(selectedPlanning);
                if(tickets.Count() > availableSeats)
                {
                    errorMsg += "- Er zijn nog maar " + availableSeats.ToString() + " beschikbaar voor deze film! <br />";
                }
            }

            if(errorMsg.Equals(""))
            {
                //if (reservation != null)
                //{
                //    reservation.kaartjes = tickets;
                //    Session["Bestelling"] = reservation;
                //    Response.Redirect("/debioscoop/touchscreen/buyticket/PaymentOptions.aspx");
                //}

                //Proces collected data to Sessions
                bestelling newBestelling = new bestelling();
                newBestelling.active = true;
                newBestelling.afgehaald = true;
                newBestelling.datum = DateTime.Now.Date;
                newBestelling.soort = "koop";
                newBestelling.tijd = new TimeSpan(int.Parse(time.Substring(0, 2)), int.Parse(time.Substring(3, 2)), 0);
                newBestelling.kaartjes = tickets;
                newBestelling.brillen = int.Parse(glasses.Text);
                
                Session["Bestelling"] = newBestelling;
                if (selectedMovie.stoelen_kiezen == true)
                {
                    Response.Redirect("/debioscoop/touchscreen/buyticket/ExtraOptions.aspx");
                }
                else
                {
                    Response.Redirect("/debioscoop/touchscreen/buyticket/PaymentOptions.aspx");
                }
            }
            else
            {
                notification.Text = errorMsg;
            }
        }

        if (selectedMovie.film_id != 0)
        {
            movImage.ImageUrl = selectedMovie.url;
            movRating.Text = selectedMovie.rating.ToString();
            movTitle.Text = selectedMovie.naam;
            movYear.Text = selectedMovie.jaar.ToString();
            int j = 0;
            foreach (var genre in selectedMovie.genres)
            {
                movGenres.Text += (j == 0 ? genre.genre1.ToString() : " | " + genre.genre1.ToString());
                j++;
            }
            movSummary.Text = selectedMovie.omschrijving;
            //if (selectedMovie.drie_d == false)
            //{
            //    glassesName.Text = "";
            //    glasses.Visible = false;
            //}

            if (reservation == null)
            {
                timeList.DataSource = planningManager.getMovieTimes(selectedMovie, DateTime.Today);
            }
            else
            {
                glasses.Text = reservation.brillen.ToString();
                List<string> ReservationTime = new List<string>();
                ReservationTime.Add(string.Format("{0:00}:{1:00}", reservation.tijd.Hours, reservation.tijd.Minutes));
                timeList.DataSource = ReservationTime;
            }
            timeList.DataBind();

            availableTickets.DataSource = ticketManager.getAvailableTickets();
            availableTickets.DataBind();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, true);
        }
        else
        {
            Response.Redirect(Page.ResolveClientUrl("~/touchscreen/BuyTicket"));
        }

        Master.tl.pageTranslator(selectedMovieForm.Controls);
    }

    protected void availableTickets_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            TextBox tex = (TextBox)e.Item.FindControl("ticket");
            //add jquery
            myScript += "$(\"#" + tex.ClientID + "\").counter({minVal: 0, maxVal: 200, singleName: 'kaart', defaultName: 'kaarten' });";

            //if (reservation != null)
            //{
            //    foreach (var ticket in reservation.kaartjes)
            //    {
            //        string ticketName = ticket.abbonementabbonementnaam;
            //        string ticketNameRepeater = ((abbonement)e.Item.DataItem).abbonementnaam;
            //        if (ticketName.Equals(ticketNameRepeater))
            //        {
            //            int tempCount = int.Parse(tex.Text);
            //            tex.Text = (tempCount + 1).ToString();
            //        }
            //    }
            //}
        }
    }

    protected void timeList_DataBound(object sender, EventArgs e)
    {
        //if (reservation != null)
        //{
        //    timeList.SelectedIndex = 0;
        //}
    }
}